let mysql_client = require('mysql');

class MsqlClient {
  constructor() {
    this.config = {
      host: 'localhost',
      port: 3306,
      user: 'root',
      password: 'zhaoyj123',
      database: 'express_demo'
    }
    this.connection = null
  }

  _connect() {
    this.connection = mysql_client.createConnection(this.config);
    this.connection.connect(function (err) {
      if (err) console.error('数据库链接失败', err.message), throw err;
    })
  }

  _close() {
    this.connection.end();
  }

  execSql(sql) {
    return new Promise((resolve, reject) => {
      this._connect()
      this.connection.query(sql, function (error, results, fields) {
            if (error) console.error(error.message)
            //控制台打印结果
            console.log("execSql", results);
            resolve(results)
          }
      );
      this._close()
    })
  }
}

module.exports = {
  msqlClient: new MsqlClient()
}
